// StringsDriverLoader.cpp : Defines the entry point for the application.
//

#include "stdafx.h"


int WINAPI WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR     lpCmdLine,
                     int       nCmdShow)
{

	BOOL success = true;

	BOOL usedCommandLine = true;

	wprintf(L"StreamDriverUnload app.\r\n");

	LPCTSTR   wstream;
	wstream =(LPCTSTR) lpCmdLine;

	DWORD cmdlineLength = wcslen(wstream);
	WCHAR thisStream[] = L"COM1:";

	//Default to this sstream
	if (cmdlineLength ==0)
	{
		wstream = thisStream;
		usedCommandLine=false;
	}
	//Check for index no.
	else if (cmdlineLength ==1)
	{
		BYTE index =  (BYTE) lpCmdLine[0] - (BYTE) '0';
		if (index <9) 
		{
			thisStream[3] = (WCHAR)lpCmdLine[0];
			wstream = (LPCTSTR) thisStream;
			usedCommandLine=true;
		}
		//Otherwise default to this stream with index 1
		else
		{
			wstream = thisStream;
			usedCommandLine=false;
		}
	}
	//Otherwise default to this stream with index 1
	else if (cmdlineLength !=5)
	{
		wstream = thisStream;
		usedCommandLine=false;
	}

     HANDLE hStr = CreateFile( wstream, 
                              GENERIC_READ | GENERIC_WRITE, 
                              0, 
                              NULL, 
                              OPEN_EXISTING, 
                              0, 
                              0);

    DEVMGR_DEVICE_INFORMATION DeviceInfo = 
                          { sizeof(DEVMGR_DEVICE_INFORMATION) };
    GetDeviceInformationByFileHandle( hStr, &DeviceInfo );

	HANDLE hStr2 = DeviceInfo.hDevice; //Should be same as that returned by ActivateDeviceEx()
	wprintf(L"StreamDriverUnload App: Device HANDLE  is %X \r\n", hStr2);

    // Be sure to close the file handle before we unload the driver!
    CloseHandle( hStr );

	try
	{
		//Unload the driver
		BOOL res = DeactivateDevice( hStr2 );
		if (res)
		{
			wprintf(L"StreamDriverUnload App: Unloaded driver instance: %s \r\n", wstream);
		}
		else 
		{
			wprintf(L"StreamDriverUnloadA pp: Couldn't unload driver instance %s \r\n", wstream);
		}
	}
	catch (LPWSTR ex)
	{
		DBG_UNREFERENCED_LOCAL_VARIABLE(ex);
		wprintf(L"StreamDriverUnload App: Problem occurred unloading driver instance %s \r\n%s\r\n", wstream, ex);

	}

    return 0;
}

